package com.vimi8.chick.plugins.event.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.eros.framework.http.okhttp.callback.Callback;
import com.vimi8.chick.plugins.model.HttpResultBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

public abstract class HttpResponseCallback extends Callback<HttpResultBean> {

    @Override
    public HttpResultBean parseNetworkResponse(Response response, int id) throws Exception {
        Map<String, List<String>> responseHeader = new HashMap<>();
        for (Map.Entry<String, List<String>> entry : response.headers().toMultimap().entrySet()) {
            responseHeader.put(entry.getKey(), entry.getValue());
        }
        try {
            ResponseBody responseBody = response.body();
            boolean isTextType = false;
            if (responseBody != null) {
                MediaType mediaType = responseBody.contentType();
                if (mediaType != null) {
                    isTextType = isText(mediaType);
                }
            }
            Object resObj = response.body().string();
            if (!isTextType) {
                resObj = JSON.parse(resObj.toString());
            }
            return new HttpResultBean(response.code(), "", resObj, responseHeader);
        } catch (JSONException e) {
            e.printStackTrace();
            return new HttpResultBean(-1, "json解析错误", null, responseHeader);
        }

    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            return mediaType.subtype().equals("xml") ||
                mediaType.subtype().equals("html") ||
                mediaType.subtype().equals("webviewhtml");
        }
        return false;
    }
}
